<template>
  <div id="login-container">
    <h1>会议室预定系统-后台管理</h1>
    <el-form
      ref="formRef"
      style="max-width: 600px; margin-top: 15px"
      :model="formData"
      :rules="formRules"
      label-width="68px"
      status-icon
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="formData.password" type="password" show-password />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)" style="width: 100%">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { login } from '@/api'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'

interface ILoginForm {
  username: string
  password: string
}

const formSize = ref<ComponentSize>('default')
const formRef = ref<FormInstance>()
const router = useRouter()

const formData = reactive<ILoginForm>({
  username: '',
  password: ''
})
const formRules = reactive<FormRules<ILoginForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在1 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码不能少于6位', trigger: 'blur' }
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid, fields) => {
    if (valid) {
      const { username, password } = formData
      const res = await login(username, password)
      const { code, message: msg, data } = res.data
      if (res.status === 200 || res.status === 201) {
        ElMessage.success('登录成功')

        localStorage.setItem('access_token', data.accessToken)
        localStorage.setItem('refresh_token', data.refreshToken)
        localStorage.setItem('user_info', JSON.stringify(data.userInfo))
        setTimeout(() => {
          router.push({
            path: '/'
          })
        }, 1000)
      } else {
        ElMessage.error(data || '系统繁忙,请稍后再试')
      }
    } else {
      ElMessage.error('表单校验失败')
    }
  })
}
</script>

<style scoped lang="less">
#login-container {
  width: 400px;
  margin: 100px auto 0 auto;
  text-align: center;
}
</style>
